package com.tim.app.ui.fragment.found;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.MusicAlbum;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

/**
 * 专辑信息页面
 */
public class MusicDetailInfoFragment extends BaseFragment implements View.OnClickListener {

    public static final String TAG = "MusicDetailInfoFragment";
    private View rootView;

    private TextView tvFollow;
    private RoundedImageView rivImage;
    private TextView tvTitle;
    private TextView tvDesc;
    private TextView tvMusicAlbumDesc;

    private MusicAlbum musicAlbum;

    public static MusicDetailInfoFragment newInstance(MusicAlbum musicAlbum) {
        MusicDetailInfoFragment newFragment = new MusicDetailInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("musicAlbum", musicAlbum);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    public void updateData(MusicAlbum musicAlbum) {
        this.musicAlbum = musicAlbum;
        updateUi();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_music_album_info, container, false);
            tvFollow = (TextView) rootView.findViewById(R.id.tvFollow);
            rivImage = (RoundedImageView) rootView.findViewById(R.id.rivImage);
            tvTitle = (TextView) rootView.findViewById(R.id.tvTitle);
            tvDesc = (TextView) rootView.findViewById(R.id.tvDesc);
            tvMusicAlbumDesc = (TextView) rootView.findViewById(R.id.tvMusicAlbumDesc);
            tvFollow.setOnClickListener(this);
            rivImage.setOnClickListener(this);
            tvTitle.setOnClickListener(this);
            tvDesc.setOnClickListener(this);
        }
        Bundle args = getArguments();
        if (args != null) {
            if (args.containsKey("musicAlbum")) {
                musicAlbum = (MusicAlbum) args.getSerializable("musicAlbum");
                updateUi();
            }
        }
        return rootView;
    }

    private void updateUi() {
        if (null == musicAlbum)
            return;
        if (!TextUtils.isEmpty(musicAlbum.getIntroduce())) {
            tvMusicAlbumDesc.setText(musicAlbum.getIntroduce());
        }
        if (null != musicAlbum.getUserMsg()) {
            if (!TextUtils.isEmpty(musicAlbum.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(musicAlbum.getUserMsg().getImage(), rivImage);
            }
            if (!TextUtils.isEmpty(musicAlbum.getUserMsg().getName())) {
                tvTitle.setText(musicAlbum.getUserMsg().getName());
            }
            if (!TextUtils.isEmpty(musicAlbum.getUserMsg().getIntroduce())) {
                tvDesc.setText(musicAlbum.getUserMsg().getIntroduce());
            }
            if (UserManager.ins().isLogin()) {
                if (UserManager.ins().getUserId().equals(musicAlbum.getUserMsg().getUserId())) {
                    tvFollow.setVisibility(View.GONE);
                }
            }
            if (TextUtils.isEmpty(musicAlbum.getUserMsg().getUserId())) {
                tvFollow.setVisibility(View.GONE);
            }
        }
        if (null != musicAlbum.getActionStateMsg()) {
            if (null != musicAlbum.getActionStateMsg().getUserState()) {
                tvFollow.setSelected(true);
                tvFollow.setText(R.string.hasFollow);
            } else {
                tvFollow.setSelected(false);
                tvFollow.setText(R.string.unFollow);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFollow:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                followOrCancelFollow();
                break;
            case R.id.rivImage:
            case R.id.tvTitle:
            case R.id.tvDesc:
                User user = new User();
                if (null != musicAlbum && null != musicAlbum.getUserMsg()) {
                    user.setUserId(musicAlbum.getUserMsg().getUserId());
                }
                SomeoneHomepageActivity.start(getActivity(), user, false);
                break;

        }
    }


    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow() {
        tvFollow.setEnabled(false);
        if (null != musicAlbum.getActionStateMsg() && musicAlbum.getActionStateMsg().getUserState() != null) {
            int id = musicAlbum.getActionStateMsg().getUserState();
            API_User.ins().cancelFollow(TAG, id, UserManager.ins().getUserId(), musicAlbum.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        tvFollow.setSelected(false);
                        tvFollow.setText(R.string.unFollow);
                        musicAlbum.getActionStateMsg().setUserState(null);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(TAG, UserManager.ins().getUserId(), musicAlbum.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (musicAlbum.getActionStateMsg() == null) {
                                musicAlbum.setActionStateMsg(new ActionStateMsg());
                            }
                            musicAlbum.getActionStateMsg().setUserState(result.getRes().getConcern().getId());
                            tvFollow.setSelected(true);
                            tvFollow.setText(R.string.hasFollow);
                        }
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        if (musicAlbum.getUserMsg().getSex() == AppKey.SEX_MAN) {
                            ToastUtil.showToast("由于对方的设置，你不能关注他");
                        } else {
                            ToastUtil.showToast("由于对方的设置，你不能关注她");
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
